// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/functions/lib/check_duplicate_keys.h>

namespace kumo::pollux::functions {
    void checkDuplicateKeys(
        const MapVectorPtr &map_vector,
        const SelectivityVector &rows,
        exec::EvalCtx &context) {
        if (rows.end() == 0) {
            return;
        }
        static const char *kDuplicateKey = "Duplicate map keys ({}) are not allowed";
        TURBO_UNUSED(kDuplicateKey);

        MapVector::canonicalize(map_vector);

        auto offsets = map_vector->rawOffsets();
        auto sizes = map_vector->rawSizes();
        auto mapKeys = map_vector->mapKeys();
        context.applyToSelectedNoThrow(rows, [&](auto row) {
            if (map_vector->is_null_at(row)) {
                return;
            }
            auto offset = offsets[row];
            auto size = sizes[row];
            for (auto i = 1; i < size; i++) {
                POLLUX_DCHECK(
                    !mapKeys->is_null_at(offset + i - 1),
                    "checkDuplicateKeys should not receive null keys");
                if (mapKeys->equal_value_at(mapKeys.get(), offset + i, offset + i - 1)) {
                    auto duplicateKey = mapKeys->wrapped_vector()->toString(
                        mapKeys->wrapped_index(offset + i));
                    POLLUX_USER_FAIL(kDuplicateKey, duplicateKey);
                }
            }
        });
    }
} // namespace kumo::pollux::functions
